<?php
/**
 * File: Task.php:YCMS
 * User: xiaoyan f@yanyunfeng.com
 * Date: 15-5-7
 * Time: 下午5:08
 * @Description
 */
define('TASK_MODEL','task');
class Task extends BaseController{
    public function init()
    {
        $this->addRoute('/task','index');
        $this->addRoute('/task.view.add','viewAdd');
        $this->addRoute('/task/{id}.html','detail');
        $this->addRoute('/task.list','taskList');
        $this->addRoute('/task.temp.list','taskTempList');
        $this->addRoute('/task.add','addTask');
        $this->addRoute('/task.exists','taskExists');
        $this->addRoute('/task.record','record');
        $this->addRoute('/task.setup.user','setupUser');
        $this->addRoute('/task.temp.user','setupTempUser');
    }
    public function index(){}
    public function viewAdd(){
        $fields = DB()
            ->field('f.*')
            ->table('common_fields f')
            ->join(array(
                '[><]common_models#m'=> array('m.model_id' => 'f.model_id')
            ))
            ->where(array('m.model_name' => TASK_MODEL))
            ->where(array('f.status' => DataState::$enable))
            ->select();
        foreach($fields as $i => $f){
            $fields[$i]['rules'] = unserialize($f['rules']);
        }
        $this->render('task.add',array('fields'=>$fields));
    }

    private function checkNoticeTimeState($time){
        $startTime = $time - 60 * 5;//下限时间
        $endTime = $time + 60 * 5; //上限时间
        $uid = $this->getUserId();

        $tablePre = $this->getConfig('db_config')->getConfig('db_prefix')->getValue();
        $noticeList = DB()->table('notification_center')
            ->where('uid',$this->getUserId())
            ->where('notice_state',1)
            ->where('notice_time[>=]',$startTime)
            ->where('notice_time[<=]',$endTime)
            ->select();
        return $noticeList;
    }

    public function record(){
        $saveData = $this->checkDataNull(array(
            array('task_no',1,'操作任务参数丢失'),
            array('log',2,'请输入记录内容')
        ));
        if(($checkTime=$this->getInput()->post('notification_time')) != null){
            $checkTime = strtotime($checkTime.':00');
            if(count($this->checkNoticeTimeState($checkTime)) > 0){
                ajaxResponse(3,'该提醒时间段内已经存在其他的任务了');
            }
        }
        if(($checkTime=$this->getInput()->post('notification_time_1')) != null){
            $checkTime = strtotime($checkTime.':00');
            if(count($this->checkNoticeTimeState($checkTime)) > 0){
                ajaxResponse(3,'该提醒时间段内已经存在其他的任务了');
            }
        }
        if(trim(strip_tags($saveData['log'])) == '') ajaxResponse(2,'请输入记录内容');
        $taskData = DB()->table('task')->where('task_no',$saveData['task_no'])->get();
        if(!$taskData) ajaxResponse(3,'您要记录的任务不存在');
        $insertData = array(
            'task_id' => $taskData['task_id'],
            'record_log' => $saveData['log'],
            'record_time' => REQ_TIME,
            'record_title' => $this->getInput()->post('title'),
            'uid' => $this->getUserId()
        );
        //添加记录
        $rid = DB()->insert('task_record',$insertData);
        if($rid > 0){ //判断是否添加成功
            $notification_time = $this->getInput()->post('notification_time');
            if($notification_time){ // 添加提醒
                try{
                    $notification_time = strtotime($notification_time.':00');
                    DB()->insert('notification_center',array(
                        'uid' => $this->getUserId(),
                        'notice_time' => $notification_time,
                        'notice_title' => '咨询任务提醒',
                        'task_id' => $taskData['task_id'],
                        'notice_message' => '咨询任务编号:@<a href="#" onclick="return osw.noticeOpenTask(this);">'.$saveData['task_no'].'</a>的提醒'
                    ));
                }catch (DBException $e){}
            }
            $taskState = $this->getInput()->post('task_state');
           //if($taskState != $taskData['task_state']){ // 更新提醒状态
                $this->readNotice(array(
                    'notice_time[<=]' => REQ_TIME,
                    'uid' => $this->getUserId(),
                    'task_id' => $taskData['task_id']
                ));//更新提醒状态
           // }
            if(($taskState == TaskState::$booking || $taskState == TaskState::$up)
                && ($time1 = $this->getInput()->post('notification_time_1')) != null){
                $notification_time = strtotime($time1.':00');
                $noticeText = $taskState == TaskState::$booking ? '交款' :'上门';
                $noticeTextMessage = $taskState == TaskState::$booking ? '需要交款' :'将会上门,请关注';
                DB()->insert('notification_center',array(
                    'uid' => $this->getUserId(),
                    'notice_time' => $notification_time,
                    'task_id' => $taskData['task_id'],
                    'notice_title' => '咨询'.$noticeText.'提醒',
                    'notice_message' => '咨询编号:@<a href="#" onclick="return osw.noticeOpenTask(this);">'
                        .$saveData['task_no'].'</a>'.$noticeTextMessage.'，点击链接查看咨询详情'
                ));
            }
            $updateData = array('last_update_time'=>REQ_TIME);
            if($taskState && $taskState != $taskData['task_state']){
                $updateData['task_state']=$taskState;
            }
            $task_level1 = $this->getInput()->post('task_level1');
            if($task_level1 && $task_level1 != $taskData['task_level1']){
                $updateData['task_level1']=$task_level1;
            }
            DB()->update('task',$updateData,array('task_id'=>$taskData['task_id']));
            ajaxSuccess(array('rid'=>$rid));
        }
        ajaxResponse(4,'添加记录失败,您可以重试看看');
    }
    private function readNotice($where){
        try{
            DB()->update('notification_center',array('notice_state'=>NoticeState::$invalid),$where);
        }catch (Exception $e){}
    }
    public function detail($id){
        if(!$id) $this->message('哎呀,查询任务诡异的不见了');
        $taskData = DB()
            ->field('t.*,u.nick_name')
            ->table('task t')
            ->join(array(
                '[><]user#u' => array('u.uid'=>'t.creator')
            ))
            ->where('task_no',$id)->get();
        if(!$taskData) $this->message('哎呀,查询任务诡异的不见了');
        $records = DB()->table('task_record r')
            ->field('r.*,u.nick_name')
            ->join(array(
                '[><]user#u' => array('u.uid'=>'r.uid')
            ))
            ->where(array('task_id'=>$taskData['task_id']))
            ->where(array('ORDER' => 'record_id DESC'))
            ->select();

        $fieldsData = DB()
            ->table('common_fieldsvar cfs')
            ->field('cfs.field_value,cf.identifier,cf.title,cf.type,cf.rules')
            ->join(array(
                '[><]common_fields#cf' => array("cf.field_id" =>"cfs.field_id")
            ))
            ->where('data_id',$taskData['task_id'])
            ->where('cf.status',DataState::$enable)
            ->select();

        foreach($fieldsData as $k => $f){
            if(in_array($f['type'],array('radio','select','list'))){
                $fieldsData[$k]['rules'] = unserialize($f['rules']);
                $fieldsData[$k]['rules']['choice'] = array_value_toKey($fieldsData[$k]['rules']['choice'],'value');
                $f['value'] = $fieldsData[$k]['rules']['choice'][$f['field_value']]['text'];
            }else $f['value'] = $f['field_value'];
            $fieldsData[$k] = array(
                'title' => $f['title'],
                'value' => $f['value']
            );
        }
        $this->initTaskState();
        $allowRecord = false; //  是否允许编辑
        $uid = $this->getUserId();
        $reqTime = REQ_TIME;
        $tablePre = $this->getConfig('db_config')->getConfig('db_prefix')->getValue();
        $checkSQL = "SELECT
	count(1) AS cc
FROM
	{$tablePre}task t
INNER JOIN {$tablePre}task_record r on t.task_id = r.task_id
LEFT JOIN {$tablePre}task_tmp tmp on t.task_id = tmp.task_id
WHERE
t.task_id = {$taskData[task_id]}
AND (
	t.uid = '{$uid}'
	OR t.creator = '{$uid}'
	OR r.uid = '{$uid}'
	OR (tmp.tmp_uid = '{$uid}' and tmp.expire_time > {$reqTime})
)";
        $allowRecord = DB()->countBySql($checkSQL) > 0;
        $this->render('task.record',array(
            'list' => $records,
            'task_data' => $taskData,
            'allowRecord' => $allowRecord,
            'first_record' => $this->checkTaskRecord($taskData),
            'task_data_fields' => $fieldsData
        ));
    }
    //咨询量是偶发
    public function checkTaskRecord($taskData){
        if(!$this->groupIs('zxs')){
            return false;
        }
        $uid = $this->getUserId();
        $count = DB()->countBySql("SELECT count(1) from ycus_task_record
where uid = {$uid} and task_id = {$taskData['task_id']}");
        return $count === 0;
    }

    private function initTaskState(){
        $allState = TaskState::getState();
        $this->assign('task_state_list',$allState);
    }
    public function taskTempList(){
        $uid = $this->getUserId(); // 当前登录UID
        list($page,$size,$start) = $ret = $this->getPageAndSize($this->getDefaultSize(10));

        $tablePre = $this->getConfig('db_config')->getConfig('db_prefix')->getValue();
        list($whereSQL,$pageQuery) = $this->fetchTaskCondition(); //
        $currentTime = REQ_TIME;
        $taskCount = DB()->countBySql("SELECT COUNT(1) FROM {$tablePre}task t,
	{$tablePre}task_tmp tmp
        WHERE t.task_id = tmp.task_id AND tmp.expire_time >= {$currentTime} ".$whereSQL);
        $queryTask = "
         SELECT
	t.*, u.nick_name AS currentOwner,
	u1.nick_name AS temp_Owner
FROM
	{$tablePre}task t,
	{$tablePre}task_tmp tmp,
	{$tablePre}user AS u,
	{$tablePre}user u1
WHERE
	t.task_id = tmp.task_id
AND t.uid = u.uid
AND tmp.tmp_uid = u1.uid
AND tmp.expire_time >= {$currentTime}
{$whereSQL}
order by t.task_id desc
limit {$start},{$size}";
        $tasks = DB()->fetchAll($queryTask);
        $pageString = http_build_query($pageQuery);
        $pageString = $pageString ? '?'.$pageString : '';
        $currentPageUrl = 'task.temp.list'.$pageString;
        $pageString = $this->createWindowPageLink($currentPageUrl,$taskCount,$size);
        $renderTemplate = 'task.list_temp';
        if(isAjax()){
            $renderTemplate = 'task.list_tmp_block';
        }

        $this->initTaskState();
        $this->render($renderTemplate,array(
            'totalCount'=>$taskCount,
            'task_list'=>$tasks,
            'show_set_size'=>true,
            'current_uid' => $uid,
            'pageString'=>$pageString
        ));
    }
    private function fetchTaskCondition(){
        $whereSQL = ' ';
        $pageQuery = array();

        $searchKey = $this->getInput()->get('search_key');
        if($searchKey){//关键字搜索
            $whereSQL .= " and (contact_name like '%{$searchKey}%' or phone like '%{$searchKey}%' "
                ." or task_no like '%{$searchKey}%' or t.task_id like '%{$searchKey}%')";
            $pageQuery['search_key'] = $searchKey;
        }
        $distributionStatus = $this->getInput()->get('distributionStatus');
        if($distributionStatus != null && in_array($distributionStatus,array(1,0))){//状态搜索
            $whereSQL .= ' and has_distribution='.$distributionStatus;
            $pageQuery['distributionStatus'] = $distributionStatus;
        }
        $taskLevel = $this->getInput()->get('task_level1');
        if($taskLevel != null && in_array($taskLevel,array(1,2,3,4))){//状态搜索
            $whereSQL .= ' and task_level1='.$taskLevel;
            $pageQuery['task_level1'] = $taskLevel;
        }
        $taskLevel = $this->getInput()->get('task_level');
        if($taskLevel != null && in_array($taskLevel,array(1,2,3,4))){//状态搜索
            $whereSQL .= ' and task_level='.$taskLevel;
            $pageQuery['task_level'] = $taskLevel;
        }
        $taskStatus = $this->getInput()->get('taskStatus');
        $allTask = TaskState::getState();
        $allTask = array_keys($allTask);
        if(in_array($taskStatus,$allTask)){//状态搜索
            $whereSQL .= ' and task_state='.$taskStatus;
            $pageQuery['taskStatus'] = $taskStatus;
            $this->assign('taskStatus',$taskStatus);
        }else{
            $this->assign('taskStatus',-1);
        }

        /**** 开始时间 ****/
        $startDate = $this->getInput()->get('start_date');
        if($startDate){
            $pageQuery['start_date'] = $startDate;
            $startDate = strtotime($startDate.' 00:00:00');
            $whereSQL .= ' and create_dateline >='.$startDate;
        }
        $endDate = $this->getInput()->get('end_date');//结束时间
        if($endDate){
            $pageQuery['end_date'] = $endDate;
            $endDate = strtotime($endDate.' 23:59:59');
            $whereSQL .= ' and create_dateline <='.$endDate;
        }
        if($startDate && $endDate && $endDate < $startDate){
            $this->message('哎呀,开始时间要小于结束时间才行哟~~');
        }
        /**** 开始时间 ****/
        $update_date_start = $this->getInput()->get('update_date_start');
        if($update_date_start){
            $pageQuery['update_date_start'] = $update_date_start;
            $update_date_start = strtotime($update_date_start.' 00:00:00');
            $whereSQL .= ' and last_update_time >='.$update_date_start;
        }
        $update_date_end = $this->getInput()->get('update_date_end');//结束时间
        if($update_date_end){
            $pageQuery['update_date_end'] = $update_date_end;
            $update_date_end = strtotime($update_date_end.' 23:59:59');
            $whereSQL .= ' and last_update_time <='.$update_date_end;
        }
        if($update_date_start && $update_date_end && $update_date_end < $update_date_start){
            $this->message('哎呀更新时间不正确,开始时间要小于结束时间才行哟~~');
        }
        return array($whereSQL,$pageQuery);
    }
    /**
     * 任务列表
     */
    public function taskList(){
        $uid = $this->getUserId(); // 当前登录UID
        list($page,$size,$start) = $ret = $this->getPageAndSize($this->getDefaultSize(10));

        $tablePre = $this->getConfig('db_config')->getConfig('db_prefix')->getValue();
        list($whereSQL,$pageQuery) = $this->fetchTaskCondition(); // 任务的查询条件
        //查询任务数
        $queryTaskCount = "SELECT COUNT(1) FROM {$tablePre}task t WHERE (EXISTS (
        SELECT 1 FROM {$tablePre}task_record WHERE t.task_id = task_id AND uid = {$uid} ) OR  t.uid = {$uid})".$whereSQL;

        $queryTask = "SELECT
	(
		SELECT
			record_time
		FROM
			{$tablePre}task_record r
		WHERE
			task_id = t.task_id
		ORDER BY
			record_id DESC
		LIMIT 1
	) AS record_time,u.nick_name as currentOwner,u1.nick_name AS taskCreator,
	(
		select count(1) from {$tablePre}notification_center
		where task_id = t.task_id
	) as noticeCount,t.*
FROM
	{$tablePre}task t
INNER JOIN {$tablePre}user u on u.uid = t.uid
INNER JOIN {$tablePre}user u1 ON u1.uid = t.creator
WHERE
	(EXISTS (
		SELECT
			1
		FROM
			{$tablePre}task_record
		WHERE
			t.task_id = task_id
		AND uid = {$uid}
	)
OR  t.uid = {$uid}) {$whereSQL}
order by
 has_distribution asc,
noticeCount desc,
 task_id desc
limit {$start},{$size}";
        $queryPermissionSql = '';
        if(hasPermission('Common_Setup_Task')){
            $queryPermissionSql = 'has_distribution=0';
        }
        if(hasPermission('common_query_task')){
            $queryPermissionSql = 'has_distribution=1';
        }
        if(hasPermission('common_query_task') && hasPermission('Common_Setup_Task')){
            $queryPermissionSql = '1';
        }
        if(hasPermission('common_query_task') or hasPermission('Common_Setup_Task')){
            $queryTask = "SELECT u.nick_name as currentOwner,u1.nick_name AS taskCreator,
  (
		select count(1) from ycus_notification_center
		where task_id = t.task_id
	) as noticeCount,t.*
FROM
	{$tablePre}task t
INNER JOIN {$tablePre}user u on u.uid = t.uid
INNER JOIN {$tablePre}user u1 ON u1.uid = t.creator
WHERE {$queryPermissionSql} {$whereSQL} order by
 has_distribution asc,
noticeCount desc,
 task_id desc
limit {$start},{$size}";
            $queryTaskCount = "SELECT count(1) FROM {$tablePre}task t WHERE {$queryPermissionSql} {$whereSQL}";
        }
        //数量
        $taskCount = DB()->countBySql($queryTaskCount);

        //查询数据列表
        $tasks = DB()->fetchAll($queryTask);
        $pageString = http_build_query($pageQuery);
        $pageString = $pageString ? '?'.$pageString : '';
        $currentPageUrl = 'task.list'.$pageString;
        $pageString = $this->createWindowPageLink($currentPageUrl,$taskCount,$size);
        $renderTemplate = 'task.list';
        $this->taskStateFetch($tasks);
        if(isAjax()){
            $renderTemplate = 'block.taskList';
        }
        $this->initTaskState();

        $this->render($renderTemplate,array(
            'totalCount'=>$taskCount,
            'task_list'=>$tasks,
            'show_set_size'=>true,
            'current_uid' => $uid,
            'group_is_zxszg' => $this->groupIs('zxszg'),
            'pageString'=>$pageString
        ));
    }
    public function taskStateFetch(&$tasks){
        //TODO 修改咨询量系统状态
        foreach($tasks as $index => &$t){
            $t['addition_class'] = '';
            $t['notice_count'] = $this->getTaskNoticeCount($t['task_id']);
            if($t['has_distribution'] == 1){

                if($t['notice_count'] > 0){
                    $t['addition_class'] = 'tr_dangers';
                }
            }else{
                $t['addition_class'] = 'tr_new';
            }
        }

    }

    private function getTaskNoticeCount($taskId,$isAll = false){
        $uid = $this->getUserId(); // 当前登录UID

        $tablePre = $this->getConfig('db_config')->getConfig('db_prefix')->getValue();
        $querySelect = "SELECT
	count(1)
FROM
	{$tablePre}notification_center
WHERE
	task_id = '{$taskId}'
AND notice_state = 1
AND uid= '{$uid}'";
        if($isAll == false) {
            $querySelect .= ' AND notice_time <= '.REQ_TIME;
        }
        return DB()->countBySql($querySelect);
    }
    public function setupUser(){
        $taskNo = $this->getInput()->get('task');
        $taskIds = explode(',',$taskNo);
        if(count($taskIds) > 1){//批量分配
            DB() -> begin(); //开始事务
            try{
                foreach($taskIds as $taskId){
                    //循环更新任务归属
                    $this->setTaskUser($taskId,true);
                }
                DB()->commit();
                ajaxSuccess();
            }catch (Exception $e){
                DB()->rollback();
                ajaxResponse($e->getCode(),$e->getMessage());
            }
        }
        $this->setTaskUser($taskNo);
    }
    public function setupTempUser(){
        $taskNo = $this->getInput()->get('task');
        $taskIds = explode(',', $taskNo);
        if (count($taskIds) == 0) {
            ajaxResponse(1, '请选择要操作的任务');
        }
        $expTime = $this->input()->post('expDate');
        if (!$expTime || preg_match('/^\d{4}-\d{2}-\d{2}$/', $expTime) == false) {
            ajaxResponse(2, '请设置过期时间');
        }
        $uid = $this->getInput()->post('uid');
        if (!$uid) {
            ajaxResponse(3, '请选择转交人');
        }
        $userInfo = $this->getUserById($uid);;
        if (!$userInfo) {
            ajaxResponse(4, '转交人不存在');
        }
        DB()->begin(); //开始事务
        //批量分配
        try {
            foreach ($taskIds as $taskId) {
                //循环转交
                $this->setTempUser($taskId,$uid,$expTime);
            }
            DB()->commit();
            ajaxSuccess();
        } catch (Exception $e) {
            DB()->rollback();
            ajaxResponse($e->getCode(), $e->getMessage());
        }
    }
    private function setTempUser($taskId,$uid,$expDate){
        $where = array('task_id'=>$taskId);
        $user = DB()->table('user')->where('uid',$uid)->get();
        if(!$user){
            throw new ServiceException('没有找到接手人',4);
        }

        $taskData = DB()->table('task')->where('task_id',$taskId)->get();
        if(!$taskData){
            throw new ServiceException('没有找到要转交的任务',2);
        }
        $taskInfo = DB()
            ->table('task_tmp')
            ->where($where)
            ->get();
        $expDate = strtotime($expDate);
        if($taskInfo){
            DB()->update('task_tmp',array(
                'tmp_uid' => $uid,
                'create_time' => REQ_TIME,
                'expire_time' => $expDate,
            ),$where);
        }else{
            DB()->insert('task_tmp',array(
                'task_id' => $taskId,
                'tmp_uid' => $uid,
                'create_time' => REQ_TIME,
                'expire_time' => $expDate,
            ));
        }
        $loginUser = $this->getLoginUser();
        $noticeMsg = $loginUser['nick_name'].'将临时任务转交给了你';
        //新增提醒
        DB()->insert('notification_center',array(
            'uid' => $user['uid'],
            'notice_time' => REQ_TIME,
            'notice_title' => '任务信息提醒',
            'notice_message' => $noticeMsg,
            'task_id' => $taskId
        ));
    }

    private function setTaskUser($taskId,$return = false){
        $uid = $this->getInput()->post('uid');
        $loginUser = $this->getLoginUser();
        if($uid == $this->getUserId()){
            if($return) throw new ServiceException('哦~任务已经是您的了',1);
            ajaxResponse(1,'哦~任务已经是您的了');
        }
        $task = DB()->table('task')->where('task_id',$taskId)->get();
        if(!$task){
            if($return) throw new ServiceException('没有找到要分配的任务',2);
            ajaxResponse(2,'没有找到要分配的任务');
        }
        if($task['uid'] != $this->getUserId() && hasPermission('Common_Setup_Task') == false){
            if($return) throw new ServiceException('对不起,您无权操作此任务',3);
            ajaxResponse(3,'对不起,您无权操作此任务',$task);
        }
        if($uid == $task['uid']){
            if($return) throw new ServiceException('哦~任务已经属于该用户',1);
            ajaxResponse(1,'哦~任务已经属于该用户');
        }
        $user = DB()->table('user')->where('uid',$uid)->get();
        if(!$user){
            if($return) throw new ServiceException('没有找到接收人',4);
            ajaxResponse(4,'没有找到接收人');
        }
        try{
            $this->ajaxBasicUpdate('task',array('uid'=>$uid,'has_distribution'=>1),array('task_id'=>$task['task_id']));

            $this->saveRecord($task['task_id'],
                sprintf('<span>@%s</span>将任务归属转移给了<span>@%s</span>',
                    $loginUser['nick_name'],$user['nick_name']));
            $noticeMsg = $loginUser['nick_name'].'将咨询量分配给了你';
            //新增提醒
            DB()->insert('notification_center',array(
                'uid' => $user['uid'],
                'notice_time' => REQ_TIME,
                'notice_title' => '任务信息提醒',
                'notice_message' => $noticeMsg,
                'task_id' => $task['task_id']
            ));
            if($return) return true;
            ajaxSuccess();
        }catch (Exception $e){
            if($return) throw new ServiceException('分配任务失败,请重试',5);
            ajaxResponse(5,'分配任务失败,请重试');
        }
    }

    public function addTask(){
        $uid = $this->getUserId();
        $fields = DB()
            ->field('f.*')
            ->table('common_fields f')
            ->join(array(
                '[><]common_models#m'=> array('m.model_id' => 'f.model_id')
            ))
            ->where(array('m.model_name' => TASK_MODEL))
            ->where(array('f.status' => DataState::$enable))
            ->select();

        $notAllowNull = array(
            array('phone',1,'请输入咨询者电话'),
        );
        foreach($fields as $fs){
            if(!$fs['allow_null']){
                $msg = ($fs['type'] == 'text' ?'请输入':'请选择').$fs['title'];
                $notAllowNull[] = array('field.'.$fs['identifier'],6,$msg);
            }
        }
        $fields = array_value_toKey($fields,'identifier');
        $saveData = $this->checkDataNull($notAllowNull);
        $this->getPostData($saveData,
            'contact_name,qq,age,education,contact_state,source,search_key,major,recommend,contact_time,visitdomain,task_level,setup_now');
        //验证任务是否存在
        if($this->checkTaskExists(array('phone'=>$saveData['phone']))) ajaxResponse(7,'该咨询已经存在了,去查询一下吧');
        if($saveData['qq'] && $this->checkTaskExists(array('qq'=>$saveData['qq']))) ajaxResponse(8,'该咨询已经存在了,去查询一下吧');
        $saveData['task_no']= createUnique();
        $saveData['create_time']= date('Y-m-d H:i:s',REQ_TIME);
        $saveData['create_dateline']= REQ_TIME;
//        $saveData['last_update_time']= REQ_TIME;
        $saveData['contact_time']= $saveData['contact_time'] ? strtotime($saveData['contact_time']):'';
        $saveData['uid']= $uid;
        $saveData['task_state']= TaskState::$normal;
        $saveData['creator']= $uid;
        $saveFiledData = array();
        if(isset($saveData['field'])){
            $fieldData = $saveData['field'];
            unset($saveData['field']);

            foreach($fieldData as $k => $v){
                $saveFiledData[] = array(
                    'data_id' => 0,
                    'field_id' => $fields[$k]['field_id'],
                    'field_value' => $v
                );
            }
        }
        $this->saveTask($saveData,$saveFiledData);
    }

    private function saveRecord($taskId,$log,$uid=0){
        DB()->insert('task_record',array(
            'task_id'=>$taskId,
            'record_log'=>$log,
            'record_time'=>REQ_TIME,
            'uid'=>$uid == 0 ? $this->getUserId():$uid,
        ));
    }
    private function saveTask($taskData,$fieldData){
        $act = $this->getInput()->get('act');
        $backUrl = 'task.list';
        if($act && in_array($act,array('insert','update'))){
            $data = array('url'=>$backUrl);
            if($act == 'insert'){
                DB()->begin(); //开始事务
                $task_id = 0;
                $setupNow = $taskData['setup_now'];
                try{
                    $task_id = $this->ajaxBasicInsert('task',$taskData);

                    foreach($fieldData as $fieldValue){
                        $fieldValue['data_id'] = $task_id;
                        DB()->insert('common_fieldsvar',$fieldValue);
                    }
                    //插入操作日志
                    DB()->insert('task_record',array(
                        'task_id'=>$task_id,
                        'record_log'=>'录入了任务',
                        'record_time'=>REQ_TIME,
                        'uid'=>$taskData['uid'],
                    ));
                    if($setupNow == '1'){
                        //给前台发送消息
                        $this->sendNoticeToGroup('qt',array(
                            'notice_time' => REQ_TIME,
                            'notice_title' => '咨询录入提醒',
                            'notice_message' => '有新任务需要分配',
                            'task_id' => $task_id
                        ));
                    }
                    DB()->commit();//提交
                }catch (Exception $e){
                    DB()->rollback();//回滚
                    if($e instanceof DBException){
                        $data = DB()->all_query();
                        ajaxResponse(RetMessage::$DBError,$data);
                    }
                    ajaxResponse($e->getCode(),$e->getMessage());
                }
                $data['task_id'] = $task_id;
                $data['task_no'] = $taskData['task_no'];
                $data['url'] = 'task/'.$taskData['task_no'].'.html';
            }else if($act == 'update'){
                $task_id = $this->getInput()->post('task_id');
                if(!$task_id) ajaxResponse(205,'没有找到要修改的数据');
                $where = array('task_id'=>$task_id);
                $fieldData = DB()->table('task')->where($where)->get();
                if(!$data) ajaxResponse(205,'没有找到要修改的数据');
                $this->ajaxBasicUpdate('task',$taskData,$where);
            }
            ajaxSuccess($data);
        }
        ajaxResponse(-1,'错误的请求',$act);
    }

    private function sendNoticeToGroup($group,$notice){
        $userList = DB()->table('auth_group_access as u')
            ->field('uid')
            ->join(array(
                '[><]auth_group#g'=>array('u.group_id' => 'g.id')
            ))
            ->where('alias',$group)
            ->select();
        foreach($userList as $user){
            $notice['uid'] = $user['uid'];
            DB()->insert('notification_center',$notice);
        }
    }


    public function taskExists(){
        $checkData = array();
        if($this->input()->get('action') == 'qq'){
            $qq = $this->checkDataNull(array(
                array('qq',1,'请输入QQ号码')
            ));
            $checkData = array('qq'=>$qq);
        }else{
            $phone = $this->checkDataNull(array(
                array('phone',1,'请输入电话号码')
            ));
            $checkData = array('phone'=>$phone);
        }
        $task = $this->checkTaskExists($checkData);
        if($task){
            ajaxResponse(2,'该任务已经存在了(任务归属:@'.$task['nick_name'].'),去查询一下吧');
        }
        ajaxSuccess();
    }

    /**
     * 是否已经存在此任务
     * @param $taskData
     * @return bool exists true or false;
     */
    private function checkTaskExists($taskData){
        $task = DB()->table('task t')
            ->join(array(
                '[><]user#u'=>array('t.uid'=>'u.uid')
            ))
            ->field('t.*,u.nick_name')
            ->where($taskData)
            ->get();
        return $task;
    }
}